/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \personnelmanage\src\pages\QuotaManage\Report\InventoryAnalysisReport\components\CompanyTab.tsx
 * @Date: 2022-01-13 15:30:31
 * @LastEditTime: 2022-10-14 10:40:55
 */

import React from 'react'
import { UdTable, UdFilter, http, UdToolbar, UdMonthPicker } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import quotaApis from '@/apis/AboutQuota'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import dayjs from 'dayjs'
import { Button, Spin } from 'antd'
import { downBlobFile, randomNumber } from '@/utils/methods'
import moment from 'moment'
export default class CompanyTab extends React.Component<IProps, IState> {
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList: ReadonlyArray<any> = this.props.brandList
  private tableProps: any = { rowKey: () => randomNumber(5), scroll: { x: true } }
  private conditions: any = [
    {
      label: '品牌公司',
      id: 'brandCode',
      initialValue: this.brandList[0].value,
      render: (
        <UdSelect
          showSearch
          allowClear={false}
          options={this.brandList}
          onChange={value => {
            this.changeBrandCode(value)
          }}
        />
      ),
    },
    {
      label: '统计月份',
      id: 'stageMonth',
      initialValue: moment(),
      render: () => (
        <UdMonthPicker
          allowClear={false}
          onChange={() => { }}
          placeholder="请选择统计月份"
          style={{ width: '100%' }}
          className={'ext'}
        />
      ),
    },
    {
      label: '物料分类',
      id: 'groupCode',
      render: () => <UdSelect showSearch options={this.state.prodBarCodeList} />,
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      uploading: false,
      downloading: false,
      dataSource: [],
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      prodBarCodeList: [],
      Year: dayjs().year(),
      Month: dayjs().month() + 1,
    }
  }

  render() {
    const { Year, Month } = this.state
    const columns = [
      ['序号', 'id', (text, record, index) => index + 1, { width: '50px' }],
      { title: '品牌公司', dataIndex: 'brandName', minWidth: '60px' },
      { title: '物料分类编码', dataIndex: 'groupCode', minWidth: '80px' },
      { title: '物料分类名称', dataIndex: 'groupName', minWidth: '160px' },
      { title: '统计月份', dataIndex: 'statisticsMonth', minWidth: '80px' },
      { title: `${Year - 1}年${Month}月期末库存`, dataIndex: 'beforeSumNowRealStock', minWidth: '120px' },
      { title: `${Year}年${Month}月期末库存`, dataIndex: 'sumNowRealStock', minWidth: '120px' },
      { title: `${Month}月期末库存同比(%)`, dataIndex: 'sumNowRealStockCompare', minWidth: '120px' },
      { title: `${Year - 1}年${Month}月动销数量`, dataIndex: 'beforeSumNowAog', minWidth: '120px' },
      { title: `${Year}年${Month}月动销数量`, dataIndex: 'sumNowAog', minWidth: '120px' },
      { title: `${Month}月动销数量同比(%)`, dataIndex: 'sumNowAogCompare', minWidth: '120px' },
      { title: `${Year - 2}.11-${Year - 1}.${Month}累计动销`, dataIndex: 'beforeYearSumNowAog', minWidth: '140px' },
      { title: `${Year - 1}.11-${Year}.${Month}累计动销`, dataIndex: 'yearSumNowAog', minWidth: '140px' },
      { title: '年度累计动销同比(%)', dataIndex: 'yearSumNowAogCompare', minWidth: '120px' },
      { title: `${Year - 2}.11-${Year - 1}.${Month}月均动销`, dataIndex: 'avgBeforeYearSumNowAog', minWidth: '140px' },
      { title: `${Year - 1}.11-${Year}.${Month}月均动销`, dataIndex: 'avgYearSumNowAog', minWidth: '140px' },
      { title: '累计月均动销同比(%)', dataIndex: 'monthMoveCompare', minWidth: '120px' },
      { title: '库存/累计月均动销', dataIndex: 'stockAvgMove', minWidth: '120px' },
      { title: '理论安全值', dataIndex: 'statiCoefficient', minWidth: '80px' },
    ]
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button type="primary" onClick={this.exportTableExcel}>
              导出
            </Button>
          }
        ></UdToolbar>
        <UdTable
          loading={this.state.loading}
          columns={columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChangePage}
          {...this.tableProps}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </Spin>
    )
  }

  componentDidMount() {
    this.getTableData()
    this.changeBrandCode(this.brandList[0].value)
  }

  private exportTableExcel = () => {
    this.setState({ downloading: true })
    let params = this.filterForm.getFieldsValue()
    let { stageYear, brandCode } = params
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    http
      .post(quotaApis.downloadInventoryMovingAnalysis, { ...params, type: 1 }, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `${dayjs(stageYear).format('YYYY-MM')}-${brandName}-库存动销分析报表`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private changeBrandCode = (value: any) => {
    this.setState({ prodBarCodeList: [] }, () => {
      this.filterForm.setFieldsValue({ prodBarcode: undefined }, () => {
        this.getProdBarList(value)
      })
    })
  }

  private getProdBarList = (value: any) => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        this.setState({ prodBarCodeList })
      })
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getTableData()
    })
  }
  private handleSearch = (values: any) => {
    this.setState({ page: 1 }, () => {
      this.getTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ dataSource: [], page: 1, total: 0 }, () => {
      this.changeBrandCode(this.brandList[0].value)
      this.getTableData()
    })
  }

  private getTableData = async () => {
    this.setState({ loading: true })
    let params: Record<string, any> = { ...this.filterForm.getFieldsValue() }
    let stageMonth = params.stageMonth
    params['stageMonth'] = stageMonth ? dayjs(params.stageMonth).format('YYYY-MM') : undefined
    params['type'] = 1
    try {
      let list: any = await http.post(quotaApis.stockMoveAnalysisPage, {
        page: this.state.page,
        size: this.state.size,
        conditions: { ...params },
      })
      const dataSource = list.data?.content

      this.setState({
        dataSource,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
        Year: dayjs(params['stageMonth']).format('YYYY'),
        Month: dayjs(params['stageMonth']).format('M'),
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}

interface IProps {
  brandList: any[]
}
interface IState {
  dataSource?: any[]
  page?: any
  size?: any
  total?: any
  loading?: boolean
  prodBarCodeList: any[]
  downloading?: boolean
  uploading?: boolean
  Month?: any
  Year?: any
}
